package com.example.shop_2304.xq

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseViewFragment
import com.example.shop_2304.R
import com.example.shop_2304.adapter.CommentAdapter
import com.example.shop_2304.adapter.ImageAdapter
import com.example.shop_2304.databinding.FragmentCommentBinding
import com.example.shop_2304.room.AppDbUtils
import com.example.shop_2304.room.Comment
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.text.SimpleDateFormat


class CommentFragment : BaseViewFragment<FragmentCommentBinding>() {
    val list = mutableListOf<String>()//存放图片的
    lateinit var imageAdapter: ImageAdapter
    lateinit var commentAdapter: CommentAdapter
    override fun initView() {
        imageAdapter = ImageAdapter()
        commentAdapter = CommentAdapter()
        binding.rv.adapter = commentAdapter
        binding.rv.layoutManager = LinearLayoutManager(context)
        queryComment()//展示评论
        //点击发评论，弹出评论框
        binding.btnSend.setOnClickListener {
            val popupWindow = PopupWindow()
            popupWindow.width = LayoutParams.MATCH_PARENT
            popupWindow.height = LayoutParams.WRAP_CONTENT
            val view = LayoutInflater.from(context).inflate(R.layout.item_pop, null)
            //输入框需要有一个监听事件，然下方数字可以实时变化
            view.findViewById<EditText>(R.id.et_comment)
                .addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence?,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {

                    }

                    override fun onTextChanged(
                        s: CharSequence?,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                        if (s != null) {
                            val length = s.length
                            view.findViewById<TextView>(R.id.tv_count).text = "$length/20"
                            if (length == 20) {
                                view.findViewById<TextView>(R.id.tv_count).setTextColor(Color.RED)
                            } else {
                                view.findViewById<TextView>(R.id.tv_count).setTextColor(Color.BLACK)
                            }
                        } else {
                            view.findViewById<TextView>(R.id.tv_count).text = "0/20"
                        }
                    }

                    override fun afterTextChanged(s: Editable?) {

                    }
                })
            //点击添加图片按钮，弹出选择框，显示到对应位置
            //初始化rvimg
            view.findViewById<RecyclerView>(R.id.rv_img).adapter = imageAdapter
            view.findViewById<RecyclerView>(R.id.rv_img).layoutManager =
                GridLayoutManager(context, 3)
            view.findViewById<ImageView>(R.id.iv_add).setOnClickListener {
                if (list.size == 3) {
                    ToastUtils.showLong("不能再继续上传了")
                } else {
                    PictureSelector.create(this, 102).selectPicture()
                }
            }
            //点击发送按钮，将评论内容保存到数据库 并关闭popupwindow
            view.findViewById<Button>(R.id.btn_fs).setOnClickListener {

                AppDbUtils.getDb().getComDao().insert(
                    Comment(
                        0,
                        "",
                        SPUtils.getInstance().getString("name"),
                        SPUtils.getInstance().getString("phone"),
                        view.findViewById<EditText>(R.id.et_comment).text.toString(),
                        "${if(list.size>0) list[0] else ""}",
                        "${if(list.size>1) list[1] else ""}",
                        "${if(list.size>2) list[2] else ""}",
                        SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis())
                    )
                )
                queryComment()//实时刷新评论界面
                popupWindow.dismiss()//关闭对话框
            }
            //消失监听方法
            popupWindow.setOnDismissListener {
                list.clear()//防止再次打开时，展示已添加的图片
                imageAdapter.data.clear()
                imageAdapter.notifyDataSetChanged()
            }
            popupWindow.contentView = view
            popupWindow.isOutsideTouchable = true
            popupWindow.isFocusable = true//给焦点，不然不能输入内容
            popupWindow.showAtLocation(binding.btnSend, Gravity.BOTTOM, 0, 0)
        }
        //左滑删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val left = ItemTouchHelper.LEFT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //滑动结束后
                //先找到选中的小标
                val position = viewHolder.layoutPosition
                //先删除后台
                AppDbUtils.getDb().getComDao().delete(commentAdapter.data[position])
                //移除界面
                commentAdapter.data.removeAt(position)
                commentAdapter.notifyItemRemoved(position)
            }
        }).attachToRecyclerView(binding.rv)

    }
    //查询评论
    private fun queryComment() {
        val query = AppDbUtils.getDb().getComDao().query()
        //绑定到适配器上
        commentAdapter.data.clear()
        commentAdapter.data.addAll(query)
        commentAdapter.notifyDataSetChanged()
    }

    override fun initData() {

    }

    override fun getLayout(): Int = R.layout.fragment_comment

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            list.add(pictureBean.path)
            //给图片的适配器进行更新
            imageAdapter.data.clear()
            imageAdapter.data.addAll(list)
            imageAdapter.notifyDataSetChanged()
        }
    }

}